import pytz
import pandas as pd
from django.conf import settings
from datetime import datetime
from dateutil.parser import parse


class Util:
    tz = pytz.timezone(settings.TIME_ZONE)

    @classmethod
    def now(cls) -> datetime:
        """时区 当前时间 datetime"""
        return datetime.now(cls.tz)

    @classmethod
    def datetime_parser(cls, at: [datetime, str]) -> datetime:
        """解析时间 - > datetime"""

        if isinstance(at, str):
            return parse(at)
        return at

    @classmethod
    def datetime_fmt(cls, at: [datetime, str], fmt: str = '%Y-%m-%d %H:%M:%S') -> str:
        """datetime -> str 带时区"""
        return cls.datetime_parser(at).astimezone(cls.tz).strftime(fmt) if at else None

    @staticmethod
    def datetime_interval(
            start: [datetime, str],
            end: [datetime, str],
            freq: str = 'D',
            tz: bool = True,
            fm: str = '%Y-%m-%d %H:%M:%S'
    ) -> list:
        """获取datetime等间隔区间"""
        params = {
            'start': start,
            'end': end,
            'freq': freq
        }
        if tz:
            params['tz'] = settings.TIME_ZONE
        return [
            ite.strftime(fm)
            for ite in pd.date_range(**params)
        ]

    @staticmethod
    def ts_to_scale(ts: float, scale: int = 1000) -> int:
        """
        秒级别 转任意刻度
        :param ts: 单位秒
        :param scale: 1000
        :return:
        """
        return int(ts * scale)
